install.packages(c("tidyverse", "broom"))
library(tidyverse)
library(broom)

## Loading data
load("pres_voting_dta.RData")

## FIGURE A7 ##
## Model results in Tables A1 and A2 of the Dataverse appendix 
# Panel A
urban = pres_voting_dta %>%
  filter(year %in% c(1924, 1928, 1932, 1936, 1940, 1944)) %>%
  group_by(year) %>%
  nest() %>%
  mutate(model = data %>%
           map(~ lm(pct_dem_pres ~ pct_urban + factor(state), data = .))) %>%
  mutate(coefs = model %>% map(~ tidy(., conf.int = TRUE)),
         details = model %>% map(glance)) %>%
  unnest(coefs) %>%
  filter(term == "pct_urban") %>%
  select(year, estimate, conf.low, conf.high)

urban = urban %>%
  ggplot(aes(x = factor(year), y = estimate)) +
  geom_point() +
  geom_pointrange(aes(ymin = conf.low, ymax = conf.high)) +
  geom_hline(yintercept = 0, linetype = "dashed", 
             color = "red", size = 0.5) +
  labs(x = "Election",
       y = "Effect of % Urban \n on % Democrat") +
  theme_bw() +
  theme(legend.position = "bottom",
        legend.title = element_blank(),
        legend.margin = margin(t = -0.3, r = 0, b = 0, l = 0, unit = "cm"),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.background = element_rect(colour = "black"))

## Panel B
unemployed = pres_voting_dta %>%
  filter(year %in% c(1924, 1928, 1932, 1936, 1940, 1944)) %>%
  group_by(year) %>%
  nest() %>%
  mutate(model = data %>%
           map(~ lm(pct_dem_pres ~ pct_unemp + factor(state), data = .))) %>%
  mutate(coefs = model %>% map(~ tidy(., conf.int = TRUE)),
         details = model %>% map(glance)) %>%
  unnest(coefs) %>%
  filter(term == "pct_unemp") %>%
  select(year, estimate, conf.low, conf.high)

unemployed = unemployed %>%
  ggplot(aes(x = factor(year), y = estimate)) +
  geom_point() +
  geom_pointrange(aes(ymin = conf.low, ymax = conf.high)) +
  geom_hline(yintercept = 0, linetype = "dashed", 
             color = "red", size = 0.5) +
  labs(x = "Election",
       y = "Effect of % Unemployed \n on % Democrat") +
  theme_bw() +
  theme(legend.position = "bottom",
        legend.title = element_blank(),
        legend.margin = margin(t = -0.3, r = 0, b = 0, l = 0, unit = "cm"),
        panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.background = element_rect(colour = "black"))

